package com.puman.beautyfarmcounselor.ui.home;

import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.beautyfarmcounselor.IndexActivity;
import com.puman.beautyfarmcounselor.MainActivity;
import com.puman.beautyfarmcounselor.R;
import com.puman.beautyfarmcounselor.http.AjaxCallBack;
import com.puman.beautyfarmcounselor.ui.home.adpter.ImageAdapter;
import com.puman.beautyfarmcounselor.ui.home.model.Advertising;
import com.puman.beautyfarmcounselor.ui.home.model.HomeAchieve;
import com.puman.beautyfarmcounselor.ui.home.model.HomeFast;
import com.puman.beautyfarmcounselor.ui.home.view.CircleFlowIndicator;
import com.puman.beautyfarmcounselor.ui.home.view.ViewFlow;
import com.puman.beautyfarmcounselor.util.MethedUtil;
import com.puman.beautyfarmcounselor.util.XTHttp;
import com.puman.beautyfarmcounselor.util.config.GlobalData;
import com.puman.beautyfarmcounselor.util.config.RequestAddr;
import com.puman.beautyfarmcounselor.util.view.MultiSwipeRefreshLayout;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;


/**
 * A placeholder fragment containing a simple view.
 */
@EFragment(R.layout.fragment_main)
public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    //标题
//    @ViewById(R.id.top_title)
//    TextView topTitle;
    //刷新
    @ViewById(R.id.swiperefresh)
    MultiSwipeRefreshLayout mSwipeRefreshLayout;
    @ViewById(R.id.viewflow)
    ViewFlow viewFlow;
    //    图片指示点
    @ViewById(R.id.viewflowindic)
    CircleFlowIndicator indic;

    @ViewById(R.id.home_30d_income_content)
    TextView monthIncome;  //当月营业收入
    @ViewById(R.id.home_30d_server_content)
    TextView monthComes;//当月来店人数
    @ViewById(R.id.home_30d_order_content)
    TextView customerNo;//当月客流
    @ViewById(R.id.home_consumer_count_content)
    TextView newMemberCount;//当月新会员数
    @ViewById(R.id.fight_persontage_num)
    TextView persontageNum;  //工作进度显示
    @ViewById(R.id.home_progressBar)
    ProgressBar progressBar;//工作进度条
    @ViewById(R.id.home_order_notice_num)
    TextView orderNoticeNum;//预约提醒数
    @ViewById(R.id.home_birthday_notice_num)
    TextView birthdayNoticeNum;//生日提醒数
    @ViewById(R.id.home_callback_notice_num)
    TextView surplusNoticeNo;//院余提醒数
    @ViewById(R.id.top_title)
    TextView topTitle;

    /**
     * init variable
     */
    HomeAchieve homeAchieve;
    HomeFast homeFast;
    Advertising advertising;
    ImageAdapter imageAdapter;


    @AfterViews
    void updateView() {
        //设置子布局
        mSwipeRefreshLayout.setSwipeableChildren(R.id.home_scrollview);
        //设置监听
        mSwipeRefreshLayout.setOnRefreshListener(this);

//        imageAdapter = new ImageAdapter(getActivity());
//        viewFlow.setAdapter(imageAdapter);
//        viewFlow.setmSideBuffer(5); // 设置图片5张
//        // 轮播图的圆点
//        viewFlow.setFlowIndicator(indic);
//        viewFlow.setTimeSpan(2000);
//        viewFlow.setSelection(0); // 设置初始位置
//        viewFlow.startAutoFlowTimer(); // 启动自动播放

        initData(1);
        getData();
    }
    XTHttp xtHttp = new XTHttp();
    String url = "";
    private void getData() {
//        toRefresh();
         url = RequestAddr.homeAdvertising + "store_id=" + GlobalData.counselor.getData().getStore_code();
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (saveAdvertising(o)) {
//                    initData(3);
//                    imageAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });


         url = RequestAddr.homeResult + "staff_account=" + GlobalData.staff_account;
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (saveData(o)) {
                    initData(2);
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
            }
        });

        url = RequestAddr.homeFast + "emp_id=" + GlobalData.counselor.getData().getEmployee_id();
        xtHttp.get(url, new AjaxCallBack<Object>() {
            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (saveQuick(o)) {
                    initData(3);
                }
                mSwipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(IndexActivity.getInstace(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT).show();
                super.onFailure(t, errorNo, strMsg);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });


    }

    //初始化数据  1:标题栏  2:当月业绩  3:快捷按钮
    private void initData(int flag) {
        switch (flag) {
            case 1:
                topTitle.setText(GlobalData.counselor.getData().getName() + "(" + GlobalData.counselor.getData().getStore_name() + ")");
                break;
            case 2:
                monthIncome.setText("¥" + homeAchieve.getData().getIncome() + "");
                monthComes.setText(homeAchieve.getData().getComes_count() + "次");
                customerNo.setText(homeAchieve.getData().getPassenger_flow() + "人次");
                newMemberCount.setText(homeAchieve.getData().getNew_merber_count() + "个");
                persontageNum.setText(homeAchieve.getData().getSorts() + "%");
                if (MethedUtil.isNumeric(homeAchieve.getData().getSorts() + "")) {
                    progressBar.setProgress((int) homeAchieve.getData().getSorts());
                }
                break;
            case 3:
                orderNoticeNum.setText(homeFast.getData().getOrder_count() + "");
                birthdayNoticeNum.setText(homeFast.getData().getBirthday_remind_count() + "");
                surplusNoticeNo.setText(homeFast.getData().getSurplus_count() + "");
                break;
        }


    }


    @UiThread(delay = 3000)
    void initiateRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        getData();
        toRefresh();
    }

    private void toRefresh() {

        if (!mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
//        initiateRefresh();
    }

    @Click({R.id.back_btn, R.id.home_book_notify, R.id.home_feedback_notify, R.id.home_brithday_notify})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back_btn:
                MainActivity.getInstace().getFragmentManager().popBackStack();
                break;
            case R.id.home_feedback_notify:
//                MainActivity.getInstace().switchFragment(this, new SurplusFragment_());
//                MainActivity.getInstace().getSupportFragmentManager()
//                        .beginTransaction().hide(this).replace(R.id.content_none_bottom, MemberNoticyFragment_.builder().titleStr(MainActivity.getInstace().getResources().getString(R.string.home_callback_notice)).build()).addToBackStack(null).commit();
                MainActivity.getInstace().getSupportFragmentManager()
                        .beginTransaction().hide(this).replace(R.id.content_none_bottom, MemberVipFragment_.builder().taskFlag("2").titleStr(MainActivity.getInstace().getResources().getString(R.string.home_callback_notice)).build()).addToBackStack(null).commit();
                break;
            case R.id.home_book_notify:
                MainActivity.getInstace().tabHost.setCurrentTab(1);
                break;
            case R.id.home_brithday_notify:
                MainActivity.getInstace().getSupportFragmentManager()
                        .beginTransaction().hide(this).replace(R.id.content_none_bottom, MemberVipFragment_.builder().taskFlag("1").titleStr(MainActivity.getInstace().getResources().getString(R.string.home_birthday_notice)).build()).addToBackStack(null).commit();
//                MainActivity.getInstace().switchFragment(this, new SurplusFragment_());
//                Intent intent=new Intent();
//                intent.setClass(MainActivity.getInstace(), CustomerActivity_.class);
//                startActivity(intent);
                break;

        }
    }

    private boolean saveData(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            homeAchieve = objectMapper.readValue(object.toString(), HomeAchieve.class);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
//        MethedUtil.UtilToast(getActivity(), homeAchieve.getMsg());
        if (homeAchieve.isFlag()) {
            return true;
        } else {
            return false;
        }
    }

    private boolean saveQuick(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            homeFast = objectMapper.readValue(object.toString(), HomeFast.class);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
//        MethedUtil.UtilToast(getActivity(), homeFast.getMsg());
        if (homeFast.isFlag()) {
            return true;
        } else {
            return false;
        }
    }
    private boolean saveAdvertising(Object object) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            advertising = objectMapper.readValue(object.toString(), Advertising.class);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        for (int i = 0; i < advertising.getData().size(); i++) {
            MethedUtil.UtilLog("image:"+advertising.getData().get(i).getImgurl());
        }
        if (advertising.isFlag()) {
            // 广告轮播图

            imageAdapter = new ImageAdapter(this, advertising.getData());
//////            imageAdapter = new ImageAdapter(getActivity());
            viewFlow.setAdapter(imageAdapter);
            viewFlow.setmSideBuffer(advertising.getData().size()); // 设置图片5张
            // 轮播图的圆点
            viewFlow.setFlowIndicator(indic);
            viewFlow.setTimeSpan(2000);
            viewFlow.setSelection(0); // 设置初始位置
            viewFlow.startAutoFlowTimer(); // 启动自动播放

//            imageAdapter.notifyDataSetChanged();
            return true;
        } else {
            return false;
        }
    }

}
